from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
import scipy.cluster.hierarchy as sch

# 创建模拟数据集
X, _ = make_blobs(n_samples=100, n_features=2, centers=3, random_state=42)

# 应用凝聚式聚类
agg_clustering = AgglomerativeClustering(n_clusters=3, affinity='euclidean', linkage='ward')
agg_labels = agg_clustering.fit_predict(X)

# 绘制聚类结果
plt.scatter(X[:, 0], X[:, 1], c=agg_labels)
plt.title('Agglomerative Clustering')
plt.show()
# 生成并绘制层次聚类树（Dendrogram）
dendrogram = sch.dendrogram(sch.linkage(X, method='ward'))
plt.title('Dendrogram')
plt.show()